const express = require("express")
const router = express.Router()
const multer = require("multer")
const path = require("path")
const { join } = require("path")
const journalDB = require("../../../db/journal")
const { sensitiveVer } = require('../../../utils/sensitiveVerification')

// 日志的增删改查
router.use("/operation", require("./operation/index"))


// 权限判断
router.use((req, res, next) => {
  if (!req.session.userInfo.allowPublish) {
    return res.send({
      code: 15,
      mes: "您没有发表权限，请联系超级管理员进行添加"
    })
  }
  next()
})

// 上传md文件
let mdUpload = multer({
  storage: multer.diskStorage({
    // 文件存储的目录
    destination(req, file, cb) {
      cb(null, join(__dirname, "../../../static/journal/md"))
    },
    // 文件的名字
    filename(req, file, cb) {
      let name = req.session.userInfo._id
      let ext = path.extname(file.originalname)
      req.coverFile = "journal" + name + Date.now() + ext
      cb(null, req.coverFile)  //名字
    }
  })
}).single("file") //name名字 elemetUI默认为file

// 上传cover文件
let coverUpload = multer({
  storage: multer.diskStorage({
    // 文件存储的目录
    destination(req, file, cb) {
      cb(null, join(__dirname, "../../../static/journal/cover"))
    },
    // 文件的名字
    filename(req, file, cb) {
      let name = req.session.userInfo._id
      let ext = path.extname(file.originalname)
      req.coverFile = "journal" + name + Date.now() + ext
      cb(null, req.coverFile)  //名字
    }
  })
}).single("file") //name名字 elemetUI默认为file

// 上传md文件
router.post("/uploadMd", async (req, res) => {
  try {
    mdUpload(req, res, async err => {
      if (err) {
        return res.send({
          code: 8,
          mes: "md文件上传失败,请刷新后重试"
        })
      }
      res.send({
        code: 0,
        mes: "md文件上传成功",
        data: "/journal/md/" + req.coverFile
      })
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

// 上传cover文件
router.post("/uploadCover", async (req, res) => {
  try {
    coverUpload(req, res, async err => {
      if (err) {
        return res.send({
          code: 8,
          mes: "md文件上传失败,请刷新后重试"
        })
      }
      res.send({
        code: 0,
        mes: "cover文件上传成功",
        data: "/journal/cover/" + req.coverFile
      })
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

// 发表日志
router.post("/uploadJournal", async (req, res) => {
  try {
    let { title, des, md, cover } = req.body

    await sensitiveVer(title)
    await sensitiveVer(des)

    await journalDB.create({
      title,
      des,
      md,
      cover,
      author: req.session.userInfo._id
    })
    res.send({
      code: 0,
      mes: "日志发表成功"
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: error || "服务器异常，请稍后再试"
    })
  }
})






module.exports = router